package org.andao.security.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.andao.core.config.Constants;
import org.andao.core.support.context.SpringContextHolder;
import org.andao.core.utils.ExStringUtils;
import org.andao.security.model.OrgUnit;
import org.andao.security.model.Resource;
import org.andao.security.model.Role;
import org.andao.security.model.User;
import org.andao.security.service.OrgUnitService;
import org.andao.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;



/**
 * 实现用户查询验证服务.
 * 
 * @author Marco.hu(hzg139@163.com)
 */
@Transactional(readOnly=true)
public class UserDetailsServiceImpl  implements UserDetailsService{	
		
	@Autowired
	@Qualifier("userService")
	private UserService userService;
	
	/**
	 * 验证用户并加载用户权限
	 */
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {		
		
		User user = userService.getUserByLoginId(userName);
		if(null == user){
			throw new UsernameNotFoundException("用户："+userName + " 不存在");
		}			
			
		loadUserAuthorities(user);	
		return user;
	}
	
	
	//加载用户菜单
	public static void loadUserAuthorities(User user){
		StringBuffer userRightsIds = new StringBuffer();	// 所有权限id
		StringBuffer userTopMenuIds = new StringBuffer();	// 顶级菜单id
		
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		for (Role role : user.getRoles()) {//遍历角色
			grantedAuthorities.add(new GrantedAuthorityImpl(role.getRoleCode()));
			for(Resource res : role.getAuthoritys()){//遍历角色授权资源
				if(userRightsIds.indexOf(res.getResourceid())<0 && res.getIsDeleted() == Constants.BOOLEAN_FALSE) {
					userRightsIds.append(res.getResourceid()).append(",");
				}
				if(res.getResourceType().equals("menu") && res.getResourceLevel() == 1 && userTopMenuIds.indexOf(res.getResourceid())<0){
					userTopMenuIds.append(res.getResourceid()).append(",");
				}
			}
		}
		
		user.setAuthorities(grantedAuthorities.toArray(new GrantedAuthority[user.getRoles().size()]));
		//重新载入用户所属单位
		if(ExStringUtils.isNotEmpty(user.getUnitId())){
			OrgUnitService orgUnitService = SpringContextHolder.getBean("orgUnitService");
			OrgUnit orgUnit = orgUnitService.get(user.getUnitId());
			if(null != orgUnit)
			user.setOrgUnit(orgUnit);
		}
		user.setUserTopMenuIds(userTopMenuIds.toString());
		user.setUserRightsIds(userRightsIds.toString());		
	}

	
}
